﻿#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Hont.BlazingNodePackage
{
    public class SubCoroutineNode : Node
    {
        StandardContext mStandardContext;
        public int OutNodeCount;

        public override string Name { get { return "Sub Coroutine"; } }
        public override string Category { get { return "General"; } }
        public override Vector2 Size { get { return new Vector2(120, 55 + Mathf.Max(0, (OutNodeCount * 2) - 2) * 17); } }


        public SubCoroutineNode()
        {
            OutNodeCount = 1;
        }

        protected override void Init()
        {
            base.Init();

            UpdateOutPortList();
        }

        public override void OnAwake(Document document)
        {
            mStandardContext = Context as StandardContext;
        }

        public override IEnumerator Execute(Port port)
        {
            for (int i = 0; i < mOutPortList.Count; i += 2)
            {
                var item = mOutPortList[i];
                var itemHandle = mOutPortList[i + 1];
                var enumerator = BlazingNodeHelper.ToFixedCoroutine(ExecutePort(item));

                var coroutine = mStandardContext.MonoBehaviour.StartCoroutine(enumerator);
                itemHandle.Value = coroutine;

                yield return ExecutePort(itemHandle);
            }

            yield return true;
        }

        public override void OnDrawAttributesGUI(out bool updateUI)
        {
            updateUI = false;
#if UNITY_EDITOR
            EditorGUI.BeginChangeCheck();
            OutNodeCount = EditorGUILayout.IntField("Out Node Count", OutNodeCount);
            if (EditorGUI.EndChangeCheck())
            {
                UpdateOutPortList();
                updateUI = true;
            }
#endif
        }

        void UpdateOutPortList()
        {
            mOutPortList.Clear();

            for (int i = 0; i < OutNodeCount; i++)
            {
                mOutPortList.Add(new Port() { Host = this, Name = "Out" + i });
                mOutPortList.Add(new Port() { Host = this, Name = "Handle" });
            }
        }
    }
}
